package com.lagou.handler;

import com.lagou.proto.RpcRequest;
import com.lagou.proto.RpcResponse;
import com.lagou.service.UserServiceImpl;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */

@ChannelHandler.Sharable
@Service
public class RequestHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //1.如果是远程请求RpcRequest，就处理
        if (msg instanceof RpcRequest) {
            RpcRequest rpcRequest = (RpcRequest) msg;
            //接口名称
            String className = rpcRequest.getClassName();
            Class clazz = Class.forName(className);
            Object obj = applicationContext.getBean(clazz);
            String methodName = rpcRequest.getMethodName();
            Method method = clazz.getMethod(methodName, rpcRequest.getParameterTypes());
            //调用方法，结果写回到客户端
            Object result = method.invoke(obj, rpcRequest.getParameters());

            RpcResponse rpcResponse = new RpcResponse();
            rpcResponse.setRequestId(rpcRequest.getRequestId());
            rpcResponse.setResult(result);

            ctx.writeAndFlush(rpcResponse);
        }

    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
